/**
 * 项目名：五位一体化工安全信息平台
 * 日期：    2019-12-07 21:54:56
 * Copyright (c) 2015- joysuch-版权所有
 */

package com.joysuch.wwyt.bp.controller;

import cn.afterturn.easypoi.word.WordExportUtil;
import cn.zlg.common.springmvc.validate.constraints.NotNull;
import com.google.common.base.Joiner;
import com.joysuch.wwyt.bp.bean.BpWorkSafetyApplyFireListBean;
import com.joysuch.wwyt.bp.bean.BpWorkSafetyApplyUserDetailBean;
import com.joysuch.wwyt.bp.bean.BpWorkSafetyCertDetailBean;
import com.joysuch.wwyt.bp.bean.safetyworkcert.BpWorkSafetyCertBreakGroundEditBean;
import com.joysuch.wwyt.bp.bean.safetyworkcert.BpWorkSafetyCertSearchBean;
import com.joysuch.wwyt.bp.entity.BpWorkSafetyCert;
import com.joysuch.wwyt.bp.enums.SafetyWorkTypes;
import com.joysuch.wwyt.bp.service.BpWorkSafetyCertService;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.shiro.util.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/bp/work-safety-apply-dongtu")
@Api(tags = "/bp/work-safety-apply-dongtu 动土")
public class BpWorkSafetyCertBreakGroundController {

    private static final Logger logger = LoggerFactory.getLogger(BpWorkSafetyCertBreakGroundController.class);

    @Autowired
    private BpWorkSafetyCertService bpWorkSafetyCertService;

    @RequestMapping(value = "add", method = RequestMethod.POST)
    @ApiOperation("添加")
    public Object add(@Valid @RequestBody BpWorkSafetyCertBreakGroundEditBean entity) {
//        try {
        // bpWorkSafetyApplyFireService.add(entity);
        String module = "动土安全作业证";
        BpWorkSafetyCert cert = bpWorkSafetyCertService.add(entity, SafetyWorkTypes.DONG_TU, module);
        return ResultBean.success(cert);
//        } catch (Exception e) {
//            logger.error("创建失败", e);
//            return ResultBean.fail(101, "创建失败");
//        }
    }

    @RequestMapping("update")
    public Object update(@Valid @RequestBody BpWorkSafetyCertBreakGroundEditBean entity) throws Exception {
//        try {
        if (entity.getId() == null) {
            return ResultBean.fail(102, "未指定主键");
        }
        // bpWorkSafetyApplyFireService.update(entity);
        String module = "动土安全作业证";
        BpWorkSafetyCert cert = bpWorkSafetyCertService.update(entity, SafetyWorkTypes.DONG_TU, module);
        return ResultBean.success(cert);
//        } catch (Exception e) {
//            logger.error("更新失败：#" + entity.getId(), e);
//            return ResultBean.fail(101, "更新失败");
//        }
    }

    @RequestMapping("page")
    public Object page(Pageable page, BpWorkSafetyCertSearchBean condition) {
        try {
            // Page<BpWorkSafetyApplyFireListBean> data = bpWorkSafetyApplyFireService.findByPage(page, condition);
            Page<BpWorkSafetyApplyFireListBean> data = bpWorkSafetyCertService.findByPage(page, condition,
                    SafetyWorkTypes.DONG_TU);
            return ResultBean.pageData(data.getContent(), data.getTotalElements());
        } catch (Exception e) {
            logger.error("分页查询失败", e);
            return ResultBean.fail(101, "分页查询失败");
        }
    }

    @GetMapping("get")
    public Object getById(Long id) {
        try {
            Assert.notNull(id, "id不能为空");
            //  BpWorkSafetyApplyFireEditBean data = bpWorkSafetyApplyFireService.findDetailById(id);
            // BpWorkSafetyApplyFireEditBean data = bpWorkSafetyCertService.findDetailByIdFire(id);
            BpWorkSafetyCertDetailBean bean = bpWorkSafetyCertService.getById(id);
            return ResultBean.success(bean);
        } catch (Exception e) {
            logger.error("查询详情失败", e);
            return ResultBean.fail(101, "查询详情失败:" + e.getMessage());
        }
    }

    @RequestMapping("delete")
    public Object delete(Long id) {
        try {
            // bpWorkSafetyApplyFireService.delete(id);
            bpWorkSafetyCertService.delete(id);
            return ResultBean.success("");
        } catch (Exception e) {
            logger.error("删除失败", e);
            return ResultBean.fail(101, "删除失败");
        }
    }

    //作业证导出
    @RequestMapping("apply-dongtu-list")
    public void SimpleWordExport(HttpServletRequest request, HttpServletResponse response, @Valid @NotNull(field = "id") Long id) throws IOException {
        Map<String, Object> map = bpWorkSafetyCertService.getDongTuSafetyMap(id);

        try {
            XWPFDocument doc = WordExportUtil.exportWord07(
                    "template/作业证(动土).docx", map);
            FileOutputStream fos = new FileOutputStream("D:/excel/动土作业证.docx");
            doc.write(fos);
            fos.close();
            String image = "D:/excel/动土作业证.docx";
            File imageFile;
            imageFile = new File(image);
            response.setContentType(getContentType(imageFile));
            // 1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
            // 2.设置文件头：最后一个参数是设置下载文件名(假如我们叫a.pdf)
            String filename = "动土作业证.docx";
            String agent = request.getHeader("User-Agent");
            if (agent.contains("MSIE")) {
                // IE浏览器
                filename = URLEncoder.encode(filename, "utf-8");
                filename = filename.replace("+", " ");
            } else {
                // 其它浏览器
                filename = URLEncoder.encode(filename, "utf-8");
            }
            response.setHeader("Content-Disposition", "attachment;fileName=" + filename);
            if (imageFile.exists()) {
                byte[] cache = new byte[2048];
                int len = 0;
                FileInputStream fis = new FileInputStream(imageFile);
                while ((len = fis.read(cache)) != -1) {
                    response.getOutputStream().write(cache, 0, len);
                }
                fis.close();
                response.getOutputStream().flush();
            } else {
                response.setStatus(404);
                response.getOutputStream().flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getContentType(File imageFile) {
        return "multipart/form-data";
    }

}
